/*
  some function to update g_task_list
  g_task_list is a global datastrure represent tasks
  in a view
 */

// clean old tasks and show current task
function global_show_task_list()
{
    global_clean_task();
    for(i = 0; i < g_task_list.length; ++i)
    {
        generate_task(g_task_list[i]);
    }
}

// clean all old tasks dom object
function global_clean_task()
{
    $("#task_list").empty();
}

function global_get_task(id)
{
    for(i = 0; i < g_task_list.length; ++i)
    {
        if (g_task_list[i]['task_id'] == id)
        {
            return g_task_list[i];
        }
    }
}

// update task
function global_update_task(task)
{
    for(i = 0; i < g_task_list.length; ++i)
    {
        if (g_task_list[i]['task_id'] == task['task_id'])
        {
            g_task_list[i] = task;
            return;
        }
    }
}

// append task to g_task_list
function global_append_task(task)
{
    g_task_list.push(task);
}

function global_need_show(task)
{
    if (g_show_state == 0)
        return true;

    if (g_show_state == -1)
    {
        if (task['state'] != g_task_state['discard'])
            return true;
        return false;
    }
    if (g_show_state == task['state'])
        return true;
    return false;
}

// append a task dom object
// a task obj contain some dom object
function generate_task(task)
{
    tid = task['task_id'];
    if (!global_need_show(task))
        return;
    divval = '<div id="' + tid;
    divval += '"><input type="checkbox" /><input type="button" value="delete" /><input type="button" value="detail" /><span></span><input type="text" class=\"inputbox\" /></div>';
    $("#task_list").append(divval);

    $("#" + tid + ' > span').html(get_latest_name(task['node']));
    $("#" + tid + ' > input[type="text"]').hide();
    
    $("#" + tid + ' > span').attr('task_action', 'label');
    $("#" + tid + ' > input[type="text"]').attr('task_action', 'box');
    $("#" + tid + ' > input[type="checkbox"]').attr('task_action', 'select');
    $("#" + tid + ' > input[type="button"][value="delete"]').attr('task_action', 'delete');
    $("#" + tid + ' > input[type="button"][value="detail"]').attr('task_action', 'detail');
    
    $("#" + tid + ' > span').click(task_dom_click);
    $("#" + tid + ' > input[type="checkbox"]').click(task_dom_click);
    $("#" + tid + ' > input[type="button"]').click(task_dom_click);
    
    $("#" + tid + ' > span').attr('class', 'normal');
    
    taskdata = global_get_task(tid);
    // if task is done
    if (taskdata['state'] == g_task_state['done'])
    {
        $("#" + tid + ' > input[type="checkbox"]').attr('checked', true);
        $("#" + tid + ' > span').attr('class', 'done');
    }
}

function global_format_date(seconds)
{
    d = read_time(seconds);
    if (!d)
        return;
    strdate = '';
    strdate += d.getFullYear() + '-';
    m = d.getMonth() + 1;
    if (m < 10)
        strdate += '0';
    strdate += m + '-';
    d = d.getDate();
    if (d < 10)
        strdate += '0';
    strdate += d;
    
    return strdate;
}

// show task detail
function show_task_detail(id)
{
    task = global_get_task(id);
    if (!task)
    {
        print('GET TASK DATA FAIL.');
        return;
    }

    val = '';
    /*for (i = 0; i < task['node'].length ; ++i)
    {
        val += '<p>' + task['node'][i][0] + '</p>';
        }*/

    val += '<p>' + get_latest_name(task['node']) + '</p>';
    val += 'duetime<input type="text" id="task_duetime"></input>';
    // val += 'remindertime<input type="text" id="task_remindertime"></input>';
    $('#task_detail').empty();
    $('#task_detail').append(val);
    $('#task_detail').attr('task_id', id);

    $('#task_duetime').val(global_format_date(get_latest_duetime(task['node'])));
    $('#task_duetime').attr('enable', false);
    // $('#task_duetime').
    // $('#task_remindertime').val(global_format_date(get_latest_remindertime(task['node'])));
    
    init_calender();
}

function task_dom_click()
{
    if (!$(this).attr('task_action'))
    {
        return;
    }

    obj = $(this).parent();
    id = obj.attr('id');
    
    // get action type
    switch ($(this).attr('task_action'))
    {
    case 'label':
        swap_lable_to_textbox(obj.attr('id'));
        break;
    case 'box':
        // swap_textbox_to_lable(obj.attr('id'));
        break;
    case 'select':
        set_task_state(obj.attr('id'));
        break;
    case 'delete':
        discard_task(obj.attr('id'));
        break;
    case 'detail':
        show_task_detail(id);
        break;
    default:
        break;
    }
}

// set task status to finish or not
function set_task_state(id)
{
    obj = $('#' + id);
    selectbox = $("#" + id + ' > input[type="checkbox"]');
    if (!obj || !selectbox)
        return;

    // get status
    var state = 'normal';
    if (selectbox.attr('checked'))
        state = 'done';
    post_set_state(id, state, set_task_state_callback);

    function set_task_state_callback(jobj)
    {
        output_clean();
        if (jobj['success'])
        {
            print('<b>SET STATE SUCCESS</b>');
        }
        else
        {
            print('<b>SET STATE FAIL</b>');
            return;
        }

        task = jobj['task'];
        // if set state success, update task
        if (task)
        {
            global_update_task(task);
            global_show_task_list();
        }
    }
}

// discard task, discarded task is exist
function discard_task(id)
{
    if (!obj)
        return;
    post_set_state(id, 'discard', discard_task_callback);
    
    function discard_task_callback(jobj)
    {
        output_clean();
        if (jobj['success'])
        {
            print('<b>DISCARD TASK SUCCESS</b>');
        }
        else
        {
            print('<b>DISCARD TASK FAIL</b>');
            return;
        }

        task = jobj['task'];
        // if set state success, update task
        if (task)
        {
            global_update_task(task);
            global_show_task_list();
        }
    }
}

// user show a task details and then he select another date
function change_task_date(dateText)
{
    obj = $(this).parent();
    id = obj.attr('task_id');
    task = global_get_task(id);
    if (!obj || !id || !task)
        return;

    oldtime = read_time(get_latest_duetime(task['node']));
    strtime = $(this).val();
    if (strtime.length != 10 || dateText.charAt(4) != '-'
        || dateText.charAt(7) != '-')
        return;
    y = parseInt(dateText.substring(0, 4));
    m = parseInt(dateText.substring(5, 7));
    d = parseInt(dateText.substring(8, 10));
    if (y == oldtime.getFullYear() && m == oldtime.getMonth() + 1
        && d == oldtime.getDate())
        return;
    
    // post request
    post_commit_duetime(id, write_time(y, m, d), commit_duetime_callback);

    // call back function
    function commit_duetime_callback(jobj)
    {
        if (jobj['success'])
        {
            print('<b>COMMIT DUETIME SUCCESS</b>');
        }
        else
        {
            print('<b>COMMIT DUETIME FAIL</b>');
            return;
        }
        // if commit success, we will convert new_task to normal task
        global_update_task(jobj['task']);
        // refresh detail page
        $("#" + jobj['task']['task_id'] + ' > input[type="button"][value="detail"]').click();
    }
}

function swap_lable_to_textbox(id)
{
    obj = $('#' + id);
    box = $("#" + id + ' > input[type="text"]');
    label = $("#" + id + ' > span');

    label.hide();
    box.attr('value', label.text());
    box.show();
    
    box.focus();
    box.keydown(function(event) {
            // press 'ENTER'
            if (event.keyCode == 13)
                box.blur();
        });
    
    box.blur(swap_textbox_to_lable);
}

// user select(click) a lable for editing
// after he/she done, this function will be called
function swap_textbox_to_lable()
{
    obj = $(this).parent();
    id = obj.attr('id');
    box = $("#" + id + ' > input[type="text"]');
    label = $("#" + id + ' > span');

    //
    var postname = box.attr('value');
    var currentname = get_latest_name(global_get_task(id)['node']);
    
    label.text(currentname);
    label.show();
    box.hide();
    
    // if text changes, post commit
    if (postname != currentname)
    {
        post_commit_name(id, postname, commit_post_callback);
    }
}

function simple_list_task()
{
    post_list_owner_task('spike', list_post_callback);
}

// some function for task

function get_latest_name(node)
{
    return node[node.length - 1][0];
}
function get_latest_duetime(node)
{
    return node[node.length - 1][1];
}
function get_latest_remindertime(node)
{
    return node[node.length - 1][2];
}

function do_create_task()
{
    output_clean();
    print('create new task');
    
    // post create request
    if($(this).attr('value') != '')
    {
        post_create_task($(this).attr('value'),
                         get_time(), get_time() + 86400,
                         'description_none', do_create_task_callback);
    }
    // create task name is empty, it should not post create request
    else
    {
        $("#new_task").remove();
        $("#new_task_box").remove();
    }

    function do_create_task_callback(jobj)
    {
        if (jobj['success'])
        {
            print('<b>CREATE TASK SUCCESS</b>');
        }
        else
        {
            print('<b>CREATE TASK FAIL</b>');
            return;
        }
        // if create success, we will convert new_task to normal task
        global_append_task(jobj['task']);
        global_show_task_list();
    }
}


function create_task()
{
    divval = '<div id="new_task" />';
    $("#task_list").append(divval);
    $("#new_task").hide();

    divval = '<input type="text" id="new_task_box" />';
    $("#task_list").append(divval);
    $("#new_task_box").focus();

    $("#new_task_box").blur(do_create_task);
    
    $("#new_task_box").keydown(function(event){
            if (event.keyCode == 13)
                $("#new_task_box").blur();
        });
}


function list_post_callback(jobj)
{
    if (jobj['success'])
    {
        print('<b>SUCCESS</b>');
    }
    else
    {
        print('<b>FAIL</b>');
        return;
    }

    g_task_list = jobj['task_list'];
    global_show_task_list();
}

// 
function commit_post_callback(jobj)
{
    output_clean();
    if (jobj['success'])
    {
        print('<b>Commit Success</b>');
    }
    else
    {
        print('<b>Commit FAIL</b>');
        return;
    }

    task = jobj['task'];
    if (task)
    {
        global_update_task(task);
        global_show_task_list();
    }
}

function init_calender()
{
    $.datepicker.regional['zh-CN'] = {
        clearText: '清除', clearStatus: '清除已选日期',
        closeText: '关闭', closeStatus: '不改变当前选择',
        prevText: '&lt;上月', prevStatus: '显示上月',
        nextText: '下月&gt;', nextStatus: '显示下月',
        monthNames: ['一月','二月','三月','四月','五月','六月',
                     '七月','八月','九月','十月','十一月','十二月'],
        monthNamesShort: ['一','二','三','四','五','六',
                          '七','八','九','十','十一','十二'],
        dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
        dayNamesMin: ['日','一','二','三','四','五','六'],
        dayStatus: '设置 DD 为一周起始', dateStatus: '选择 m月 d日, DD',
        dateFormat: 'yy-mm-dd', firstDay: 1,
        initStatus: '请选择日期', isRTL: false
    };


    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#task_duetime").datepicker({showOn: 'focus', onSelect: change_task_date});
    // $("#task_remindertime").datepicker();
}

function init()
{
    simple_list_task();
    $("#create_task").click(create_task);
}

function print(val)
{
    $("#output").append("<p>" + val + "</p>");
}

function output_clean()
{
    $("#output").html('');
}

g_task_list = {};
g_task_state = {
    'normal': 1,
    'alarm': 2,
    'done': 3,
    'discard': 4
};
g_show_state = -1;
$(document).ready(init);
